import config from '@/config'
import storage from '@/utils/storage'
import constant from '@/utils/constant'
import { isHttp, isEmpty } from "@/utils/validate"
import { login2, logout, getInfo, getUserInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import defAva from '@/static/images/profile.jpg'

const baseUrl = config.baseUrl

const user = {
  state: {
    token: getToken(),
    id: storage.get(constant.id),
    name: storage.get(constant.name),
    avatar: storage.get(constant.avatar),
    roles: storage.get(constant.roles),
    permissions: storage.get(constant.permissions),
    dept: storage.get(constant.dept),
    company: storage.get(constant.company),
    postName: storage.get(constant.postName),
    spaceName: storage.get(constant.spaceName),
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_ID: (state, id) => {
      state.id = id
      storage.set(constant.id, id)
    },
    SET_NAME: (state, name) => {
      state.name = name
      storage.set(constant.name, name)
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
      storage.set(constant.avatar, avatar)
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
      storage.set(constant.roles, roles)
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
      storage.set(constant.permissions, permissions)
    },
    SET_DEPT: (state, dept) => {
      // 确保 dept 是对象
      state.dept = dept || {}
      // 存储时转换为 JSON 字符串
      storage.set(constant.dept, JSON.stringify(dept))
    },
    SET_COMPANY: (state, company) => {
      state.company = company 
      storage.set(constant.company, company)
    },
    SET_POST_NAME: (state, postName) => {
      state.postName = postName 
      storage.set(constant.postName, postName)
    },
    SET_SPACE_NAME: (state, spaceName) => {
      state.spaceName = spaceName 
      storage.set(constant.spaceName, spaceName)
    }
  },

  actions: {
    // 登录
    Login2({ commit }, userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      // const code = userInfo.code
      const uuid = userInfo.uuid
      return new Promise((resolve, reject) => {
        login2(username, password, uuid).then(res => {
          setToken(res.data)
          commit('SET_TOKEN', res.data)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getUserInfo().then(res => {
          console.log('GetInfo', res);

          const user = res.data.user
          let avatar = user.avatar || ""
          if (!isHttp(avatar)) {
            avatar = (isEmpty(avatar)) ? defAva : baseUrl + avatar
          }
          const userid = (isEmpty(user) || isEmpty(user.userId)) ? "" : user.userId
          const username = (isEmpty(user) || isEmpty(user.nickName)) ? "" : user.nickName
          const company = user.company
          const postName = user.postName
          const spaceName = user.spaceName
          console.log('GetInfo user', company,
            postName,
            spaceName);


          if (user.roles && user.roles.length > 0) {
            commit('SET_ROLES', user.roles)

          } else {
            commit('SET_ROLES', ['ROLE_DEFAULT'])
          }

          commit('SET_ID', userid)
          commit('SET_NAME', username)
          commit('SET_AVATAR', avatar)
          commit('SET_PERMISSIONS', res.data.permissions)
          commit('SET_DEPT', user.dept)
          commit('SET_COMPANY', user.company)
          commit('SET_POST_NAME', user.postName)
          commit('SET_SPACE_NAME', user.spaceName)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_DEPT', {})
          commit('SET_PERMISSIONS', [])
          commit('SET_ID', '')
          commit('SET_NAME', '')
          commit('SET_AVATAR', defAva)
          commit('SET_COMPANY', '')
          commit('SET_POST_NAME', '')
          commit('SET_SPACE_NAME', '')
          removeToken()
          storage.clean()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}

export default user
